package gui;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;

import javax.swing.JPanel;

import util.Constants;
import entity.Board;
import entity.Poem;
import entity.Row;
import entity.Word;

/**
 *	This is the BoardCanvas class. 
 */
public class BoardCanvas extends JPanel {
	private static final long serialVersionUID = -3427789510043976561L;
	
	private Board board;

	/**
	 * Constructor of BoardCanvas.
	 */
	public BoardCanvas(Board board){
		this.board = board;
	} 

	@Override
	public void paintComponent(Graphics g) {
		update(g);
	}

	/**
	 * Update the Graphics.
	 */
	public void update(Graphics g) {
		Graphics2D graph = (Graphics2D) g;

		refreshBoard(graph);

		for(Word w : board.getUnprotectedWords()){
			drawWord(w, Color.WHITE, graph);
		}

		for(Word w : board.getProtectedWords()){
			drawWord(w, new Color(230, 240, 210), graph);
		}

		for(Poem p : board.getPoems()){
			for(Row r : p.getRows()){
				for(Word w : r.getWords()){
					drawWord(w, new Color(210, 230, 240), graph);
				}
			}
		}
	}
	
	/**
	 * Draw the background box for a word.
	 */
	public void drawWord(Word w, Color c, Graphics2D graph){
		if(w.getWidth() == 0){
			initializeWord(graph, w);
		}
		
		graph.setStroke(new BasicStroke(4f));
		Rectangle rect = new Rectangle(w.getX(), w.getY(), w.getWidth(), w.getHeight());
		
		graph.setColor(Color.black);
		graph.draw(rect);

		Color fillColor = c;
		Color textColor = Color.BLACK;

		if(w.blink){
			w.blink = false;
			fillColor = Color.BLACK;
			textColor = Color.WHITE;
		}
		
		graph.setColor(fillColor);
		graph.fill(rect);

		graph.setFont(new Font("Arial", Font.BOLD, 12));
		graph.setColor(textColor);
		graph.drawString(w.getValue(), rect.getLocation().x + 10, rect.getLocation().y + 20);
		
	}

	/**
	 * Refresh the Board.
	 */
	public void refreshBoard(Graphics2D g){
		g.setPaint(new Color(170, 170, 220));
		g.fillRect(0, 0, Constants.BOARD_WIDTH, Constants.PROTECTED_AREA_HEIGHT);

		g.setPaint(new Color(150, 255, 150));
		g.fillRect(0, Constants.PROTECTED_AREA_HEIGHT, Constants.BOARD_WIDTH, Constants.UNPROTECTED_AREA_HEIGHT);
	}
	
	public void initializeWord(Graphics2D graph, Word w){
		int width = graph.getFontMetrics().stringWidth(w.getValue()) + 20;
		int height = 30;

		w.setWidth(width);
		w.setHeight(height);
		
		board.randomizeUnprotectedWord(w);
	}

}
